package com.example.backend.service;

import com.example.backend.annotation.LogExecution;
import com.example.backend.domain.entity.Ticket;
import com.example.backend.domain.entity.User;
import com.example.backend.domain.enums.TicketStatus;
import com.example.backend.repository.TicketRepository;
import com.example.backend.service.async.TicketAsyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;

/**
 * 优化的工单服务
 * 快速响应 + 异步处理复杂业务逻辑
 */
@Service("ticketServiceOptimized")
public class TicketServiceOptimized {
    
    private static final Logger log = LoggerFactory.getLogger(TicketServiceOptimized.class);
    
    private final TicketRepository ticketRepository;
    private final TicketAsyncService ticketAsyncService;
    
    public TicketServiceOptimized(
            TicketRepository ticketRepository,
            TicketAsyncService ticketAsyncService) {
        this.ticketRepository = ticketRepository;
        this.ticketAsyncService = ticketAsyncService;
    }
    
    /**
     * 创建工单（优化版）
     * 核心思路：
     * 1. 快速完成必要的数据库操作
     * 2. 立即返回响应
     * 3. 异步处理复杂业务逻辑（历史记录、邮件、通知等）
     */
    @LogExecution("创建工单（优化版）")
    @Transactional
    @CacheEvict(value = {"tickets", "tickets_list", "tickets_stats"}, allEntries = true)
    public Ticket createOptimized(Ticket ticket, User creator) {
        String serviceId = "OPT-SVC-" + System.currentTimeMillis();
        long startTime = System.currentTimeMillis();
        
        try {
            log.info("╔═══════════════════════════════════════════════════════════════");
            log.info("║ [{}] ⚡ 开始优化版工单创建", serviceId);
            log.info("╠═══════════════════════════════════════════════════════════════");
            log.info("║ 工单标题: {}", ticket.getTitle());
            log.info("║ 创建者: {}", creator.getUsername());
            log.info("║ 策略: 快速保存 + 异步处理");
            log.info("╚═══════════════════════════════════════════════════════════════");
            
            // ============================================
            // 第一阶段：快速完成核心操作（同步）
            // ============================================
            
            // 1. 设置默认值
            long step1Start = System.currentTimeMillis();
            if (ticket.getStatus() == null) {
                ticket.setStatus(TicketStatus.OPEN);
            }
            ticket.setCreatedBy(creator);
            if (ticket.getCustomer() == null) {
                ticket.setCustomer(creator);
            }
            log.debug("[{}] ✓ 默认值设置完成 - {}ms", serviceId, System.currentTimeMillis() - step1Start);
            
            // 2. 生成工单编号
            long step2Start = System.currentTimeMillis();
            String ticketNumber = generateTicketNumber();
            ticket.setTicketNumber(ticketNumber);
            log.debug("[{}] ✓ 工单编号生成 - {}ms: {}", serviceId, 
                    System.currentTimeMillis() - step2Start, ticketNumber);
            
            // 3. 保存工单（核心操作）
            long step3Start = System.currentTimeMillis();
            Ticket savedTicket = ticketRepository.save(ticket);
            long saveTime = System.currentTimeMillis() - step3Start;
            log.info("[{}] ✓ 工单保存完成 - {}ms | ID: {}", serviceId, saveTime, savedTicket.getId());
            
            // ============================================
            // 第二阶段：触发异步处理（不阻塞）
            // ============================================
            
            // 异步处理复杂业务逻辑
            long asyncStart = System.currentTimeMillis();
            ticketAsyncService.handleTicketCreatedAsync(savedTicket, creator);
            long asyncTriggerTime = System.currentTimeMillis() - asyncStart;
            log.debug("[{}] ✓ 异步任务触发 - {}ms", serviceId, asyncTriggerTime);
            
            // ============================================
            // 完成
            // ============================================
            
            long totalTime = System.currentTimeMillis() - startTime;
            
            log.info("╔═══════════════════════════════════════════════════════════════");
            log.info("║ [{}] ✅ 优化版工单创建完成", serviceId);
            log.info("╠═══════════════════════════════════════════════════════════════");
            log.info("║ 工单ID: {}", savedTicket.getId());
            log.info("║ 工单编号: {}", savedTicket.getTicketNumber());
            log.info("║ 总耗时: {}ms", totalTime);
            log.info("║   - 核心保存: {}ms", saveTime);
            log.info("║   - 异步触发: {}ms", asyncTriggerTime);
            log.info("║ 性能提升: 异步处理中（不阻塞响应）");
            log.info("╚═══════════════════════════════════════════════════════════════");
            
            return savedTicket;
            
        } catch (Exception e) {
            log.error("╔═══════════════════════════════════════════════════════════════");
            log.error("║ [{}] ❌ 优化版工单创建失败", serviceId);
            log.error("╠═══════════════════════════════════════════════════════════════");
            log.error("║ 异常: {}", e.getMessage());
            log.error("╚═══════════════════════════════════════════════════════════════");
            log.error("异常详情:", e);
            
            throw new RuntimeException("工单创建失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 创建工单（极速版）
     * 只保存核心数据，所有其他操作全部异步
     */
    @Transactional
    @CacheEvict(value = {"tickets", "tickets_list", "tickets_stats"}, allEntries = true)
    public Ticket createUltraFast(Ticket ticket, User creator) {
        String serviceId = "ULTRA-" + System.currentTimeMillis();
        long startTime = System.currentTimeMillis();
        
        try {
            // 最小化同步操作
            ticket.setStatus(ticket.getStatus() != null ? ticket.getStatus() : TicketStatus.OPEN);
            ticket.setCreatedBy(creator);
            ticket.setCustomer(ticket.getCustomer() != null ? ticket.getCustomer() : creator);
            ticket.setTicketNumber(generateTicketNumber());
            
            // 立即保存
            Ticket savedTicket = ticketRepository.save(ticket);
            
            // 所有后续操作异步处理
            ticketAsyncService.handleTicketCreatedAsync(savedTicket, creator);
            
            long totalTime = System.currentTimeMillis() - startTime;
            log.info("⚡ [{}] 极速创建完成 - {}ms | ID: {}", serviceId, totalTime, savedTicket.getId());
            
            return savedTicket;
            
        } catch (Exception e) {
            log.error("❌ [{}] 极速创建失败: {}", serviceId, e.getMessage(), e);
            throw new RuntimeException("工单创建失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 生成工单编号
     * 优化：使用时间戳 + 随机数，避免数据库查询
     */
    private String generateTicketNumber() {
        // 格式：TK-YYYYMMDD-HHMMSS-XXXX
        // TK = Ticket
        // YYYYMMDD = 年月日
        // HHMMSS = 时分秒
        // XXXX = 4位随机数
        
        Instant now = Instant.now();
        String timestamp = now.toString()
                .replaceAll("[^0-9]", "")
                .substring(0, 14); // 取前14位数字
        
        String random = String.format("%04d", (int)(Math.random() * 10000));
        
        return String.format("TK-%s-%s", timestamp, random);
    }
    
    /**
     * 批量创建工单（优化版）
     */
    @Transactional
    @CacheEvict(value = {"tickets", "tickets_list", "tickets_stats"}, allEntries = true)
    public void createBatch(Iterable<Ticket> tickets) {
        long startTime = System.currentTimeMillis();
        int count = 0;
        
        for (Ticket ticket : tickets) {
            if (ticket.getTicketNumber() == null) {
                ticket.setTicketNumber(generateTicketNumber());
            }
            count++;
        }
        
        ticketRepository.saveAll(tickets);
        
        long totalTime = System.currentTimeMillis() - startTime;
        log.info("✅ 批量创建完成 - {}个工单, 耗时: {}ms", count, totalTime);
    }
}

